import React, { PropTypes, Component } from 'react';
import {myAjaxJson, ROOTURL, getAdminInfo} from './../publicAPI/publicAPI';

import fetch from 'isomorphic-fetch'
import Table from './Table'

class Commission extends Component {
    //初始化
    constructor(props) {
        super(props)

        this.state = {
            customers: {},
            commissions: {},
            searchResult: null,
            page: 1,    　　　　　//当前页码从1 开始
        } // 初始化状态

        this.rHeight = window.innerHeight - 55

        this.start = 0;
        this.limit = 10;

        this.nextPage = true;  //下一页
        this.prePage  = false;  //上一页
        this.maxPage = -1;

    }
    componentWillMount() {
        let adminInfo = JSON.parse(sessionStorage.getItem("adminInfo"));
        if (!adminInfo) {
            getAdminInfo(() => {
                this.getCustomerReward();
            });
        } else {
            this.getCustomerReward();
        }
    }

    //获取客户提成信息
    getCustomerReward() {
         if (this.limit === 0) {
             return;
         }
         myAjaxJson(ROOTURL + 'grip/account/search.api', 'POST',{
                 start: this.start,
                 limit: this.limit
             },(json) => {
                 let commission = [];
                 let customerIds = [];
                 json.forEach((item) => {
                     commission.push({
                         id: item.id,
                         possessorId: item.possessorId,
                         bal: item.bal
                     })
                     customerIds.push(item.possessorId);
                 })

                 let currentPage = Math.floor(this.start / this.limit) + 1;

                 if (json.length < this.limit) {
                      this.nextPage = false;
                      this.maxPage = currentPage;
                      this.limit = 0;
                 } else {
                      this.start += this.limit;
                 }

                 this.setState({
                     commissions: Object.assign({}, this.state.commissions, {[currentPage]: commission}),
                     page: currentPage
                 })

                 this.getCustomerInfo(customerIds)
             }, (error) => {
                  alert('获取客户提成数据失败')
             })
    }

    //获取客户普通信息 昵称电话等
    getCustomerInfo(cusIds) {
        if (cusIds.length <= 0) return;

        myAjaxJson(ROOTURL + 'customer/profile/search.api', 'POST', {
            where: {
                id: [
                    ['in', cusIds]
                ]
            }
        }, (data) => {
            let customers = {};
            for (let cus of data) {
                customers[cus.id] = {
                    id: cus.id,
                    phone: cus.phone,
                    dname: cus.dname
                }
            }
            this.setState({
                customers: Object.assign({}, this.state.customers, customers)
            })
        })
    }

    findCustomer(dname, phone) {
        if (dname == "" && phone == "") {
            this.setState({
                searchResult: null,
                page: 1
            })
            return ;
        }

        let params = {
            where: {}
        }

        if (dname != "") {
            params.where.dname = [['eq', dname]];
        }
        if (phone != "") {
            params.where.phone = [['eq', phone]];
        }

        myAjaxJson(ROOTURL + 'customer/profile/search.api', 'POST', params,
           (data) => {
            let customers = {};
            let customerIds = [];
            for (let cus of data) {
                customers[cus.id] = {
                    id: cus.id,
                    phone: cus.phone,
                    dname: cus.dname
                }
                customerIds.push(cus.id);
            }
            this.setState({
                customers: Object.assign({}, this.state.customers, customers)
            })
            this.searchCommmission(customerIds)
        })
    }

    searchCommmission(cusIds) {
        if (cusIds.length > 0) {
            myAjaxJson(ROOTURL + 'grip/account/search.api', 'POST',{
                    where: {
                        possessorId: [['in', cusIds]]
                    }
                },(json) => {
                    let searchResult = [];
                    json.forEach((item) => {
                        searchResult.push({
                            id: item.id,
                            possessorId: item.possessorId,
                            bal: item.bal
                        })
                    })
                    this.setState({
                        searchResult: searchResult
                    })
                }, (error) => {
                     alert('获取客户提成数据失败')
                })
        } else {
            this.setState({
                searchResult: []
            })
        }

    }

    //查找接口
    handleSearchClick(e) {
        let dname=this.refs.dname.value;
        let phone=this.refs.phone.value;
        this.findCustomer(dname,phone);
    }

    //翻页按钮
	handlePageClick(e) {//1为下一页，2为上一页
		const _buttonValue = e.target.value

        if (_buttonValue == 1) this.prePage = true;
        if (_buttonValue == 2) this.nextPage = true;

        let nextPage  = _buttonValue == 1? this.state.page + 1 : this.state.page - 1;
        if (nextPage == 1) this.prePage = false;
        if (nextPage == this.maxPage) this.nextPage = false;


        if (this.state.commissions[nextPage]) {
            this.setState({
                page: nextPage
            })
        } else if (nextPage > 0) {
            this.getCustomerReward();
        }
	}

    //render thead
    tHead() {
        let data = [
            { name: "id" },
            { name: "昵称" },
            { name: "电话号码" },
            { name:"提成"}
        ]
        const _width = {
                "0": "25%",
                "1": "25%",
                "2": "25%",
                "3": "25%"
        }

     	return data.map((item, index) => {
            return <th style = {{ width: _width[index] }}
                        role = "1"
                        key = {index}> {item.name} </th>
        })
    }

    tBody() {
         let _data = !this.state.searchResult? this.state.commissions[this.state.page] : this.state.searchResult;
         let customers = this.state.customers;
         console.log(_data);
         if (_data) {
             return _data.map(item => {
                    return( <tr key = { item.id }>
                         <td> {item.possessorId} </td>
                         <td> {customers[item.possessorId] ? customers[item.possessorId].dname : ''} </td>
                         <td> {customers[item.possessorId] ? customers[item.possessorId].phone : ''} </td>
                         <td> {(item.bal).toFixed(2)} </td>
                     </tr>)
            });
        } else {
            return null;
        }
    }

    render() {

        return (
            <div className="right-wapper" style={{height: this.rHeight}}>
                <div className="rt-wrap rt-wrap-header">
                    <div className="input-div pr">
                        <label>昵称：</label>
                        <input type="text" placeholder="请输入要查找的微信号" className="default-text"
                           ref="dname"/>
                    </div>
                    <div className="input-div">
                        <label>电话号码：</label>
                        <input type="text" placeholder="请输入要查找的电话号码" className="default-text"
                           ref="phone" />
                    </div>
                    <div className="input-div">
                        <button className="search-btn" onClick={(e) => this.handleSearchClick(e)}>查找</button>
                    </div>

                </div>

                <div className="rt-wrap">
                    <h3 className="catagory">
                        <span className="cata-title">客户列表</span>
                        <button style={{display: this.nextPage ? "block" : "none"}} className="next" value="1" onClick={(e) => this.handlePageClick(e)}></button>
                        <button style={{display: this.prePage ? "block" : "none"}}  className="prev" value="2" onClick={(e) => this.handlePageClick(e)}></button>
                    </h3>
                    <Table tHead={this.tHead.call(this)} tBody={this.tBody.bind(this)()}/>
                </div>
            </div>
        );
    }
}
export default Commission;
